import { ChatMessage, ChatSession } from '@/types';
import { deepseekChat } from '@/lib/deepseek';
import {
  conversationSummaryService,
  ConversationSummary,
} from '@/lib/conversation-summary';
import {
  HumanMessage,
  SystemMessage,
  AIMessage,
} from '@langchain/core/messages';
import {
  intentRecognitionService,
  IntentResult,
  ResponseStrategy,
  UserIntent,
} from '@/lib/intent-recognition';

/**
 * 对话上下文管理器
 * 负责管理多轮对话的上下文、记忆和连贯性
 */
export class ConversationContextManager {
  private maxContextLength: number;
  private summaryThreshold: number;
  private contextWindow: number;

  constructor(
    options: {
      maxContextLength?: number;
      summaryThreshold?: number;
      contextWindow?: number;
    } = {}
  ) {
    this.maxContextLength = options.maxContextLength || 8000;
    this.summaryThreshold = options.summaryThreshold || 10;
    this.contextWindow = options.contextWindow || 6;
  }

  /**
   * 构建对话上下文
   * @param messages 历史消息
   * @param currentMessage 当前消息
   * @param ragContext RAG检索到的上下文
   * @param userId 用户ID
   * @returns 优化后的消息列表
   */
  async buildContext(
    messages: ChatMessage[],
    currentMessage: string,
    ragContext?: string,
    userId?: string
  ): Promise<{ messages: any[]; contextInfo: any }> {
    // 1. 识别用户意图
    let intentResult: IntentResult | undefined;
    let responseStrategy: ResponseStrategy | undefined;

    if (currentMessage) {
      intentResult = await intentRecognitionService.recognizeIntent(
        currentMessage,
        messages,
        userId
      );
      responseStrategy = intentResult.suggestedResponse;
    }

    // 2. 获取最近的对话历史
    const recentMessages = this.getRecentMessages(messages);

    // 3. 检查是否需要摘要
    const shouldSummarize = recentMessages.length > this.summaryThreshold;
    let conversationSummary = '';

    let summaryData: ConversationSummary | undefined;
    if (shouldSummarize) {
      summaryData = await this.generateConversationSummary(
        recentMessages.slice(0, -this.contextWindow)
      );
      conversationSummary = summaryData?.summary || '';
    }

    // 4. 构建个性化系统提示
    const systemPrompt = this.buildPersonalizedSystemPrompt({
      conversationSummary,
      ragContext,
      hasHistory: recentMessages.length > 0,
      intentResult,
      responseStrategy,
      userId,
    });

    // 5. 构建消息序列
    const contextMessages = this.buildMessageSequence(
      recentMessages,
      currentMessage,
      systemPrompt,
      conversationSummary
    );

    // 6. 验证上下文长度
    const finalMessages = await this.validateContextLength(contextMessages);

    return {
      messages: finalMessages,
      contextInfo: {
        totalMessages: messages.length,
        recentMessages: recentMessages.length,
        hasSummary: !!conversationSummary,
        hasRagContext: !!ragContext,
        contextLength: this.estimateTokenCount(finalMessages),
        summaryData,
        intentResult,
        responseStrategy,
        userProfile: userId
          ? this.buildUserProfile(messages, userId)
          : undefined,
      },
    };
  }

  /**
   * 获取最近的消息
   */
  private getRecentMessages(messages: ChatMessage[]): ChatMessage[] {
    // 按时间排序并获取最近的消息
    const sortedMessages = [...messages].sort(
      (a, b) =>
        new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
    );

    // 获取最近的消息，但保持对话的完整性（成对的用户-助手消息）
    const recentMessages: ChatMessage[] = [];
    let userMessageCount = 0;

    for (let i = sortedMessages.length - 1; i >= 0; i--) {
      const message = sortedMessages[i];
      recentMessages.unshift(message);

      if (message.role === 'user') {
        userMessageCount++;
        if (userMessageCount >= this.contextWindow) break;
      }
    }

    return recentMessages;
  }

  /**
   * 生成对话摘要
   */
  private async generateConversationSummary(
    messages: ChatMessage[]
  ): Promise<ConversationSummary | undefined> {
    if (messages.length < 5) return undefined;

    try {
      // 检查是否需要生成摘要
      if (conversationSummaryService.shouldGenerateSummary(messages)) {
        return await conversationSummaryService.generateSummary(messages);
      }

      // 对于较短的对话，生成简单摘要
      return await conversationSummaryService.generateSummary(
        messages.slice(-10)
      );
    } catch (error) {
      console.error('生成对话摘要失败:', error);
      return undefined;
    }
  }

  /**
   * 构建个性化系统提示
   */
  private buildPersonalizedSystemPrompt(options: {
    conversationSummary?: string;
    ragContext?: string;
    hasHistory: boolean;
    intentResult?: IntentResult;
    responseStrategy?: ResponseStrategy;
    userId?: string;
  }): string {
    let systemPrompt = `你是一个智能、友好且专业的AI助手。请遵循以下原则：

1. 提供准确、有帮助的回答
2. 保持对话的连贯性和上下文相关性
3. 根据用户的问题类型调整回答风格
4. 承认不确定性，避免编造信息
5. 主动提供相关的补充信息`;

    if (options.conversationSummary) {
      systemPrompt += `\n\n**对话历史摘要：**\n${options.conversationSummary}`;
    }

    if (options.ragContext) {
      systemPrompt += `\n\n**相关文档内容：**\n${options.ragContext}\n\n请优先基于上述文档内容回答问题，如果文档内容不足以回答问题，请明确说明并提供你的最佳建议。`;
    }

    if (options.hasHistory) {
      systemPrompt += `\n\n请结合之前的对话历史，保持回答的连贯性和一致性。`;
    }

    // 添加意图识别信息
    if (options.intentResult) {
      systemPrompt += `\n\n**用户意图分析：**\n意图类型：${this.getIntentDisplayName(options.intentResult.intent)}\n置信度：${(options.intentResult.confidence * 100).toFixed(1)}%\n关键词：${options.intentResult.keywords.join(', ')}\n情感倾向：${options.intentResult.emotionalTone}`;
    }

    // 添加响应策略指导
    if (options.responseStrategy) {
      systemPrompt += `\n\n**响应策略：**\n语调风格：${this.getToneDisplayName(options.responseStrategy.tone)}\n回答长度：${this.getLengthDisplayName(options.responseStrategy.length)}\n结构方式：${this.getStructureDisplayName(options.responseStrategy.structure)}`;
    }

    return systemPrompt;
  }

  /**
   * 构建消息序列
   */
  private buildMessageSequence(
    recentMessages: ChatMessage[],
    currentMessage: string,
    systemPrompt: string,
    conversationSummary?: string
  ): any[] {
    const messages: any[] = [];

    // 添加系统消息
    messages.push(new SystemMessage(systemPrompt));

    // 如果有摘要，添加摘要信息
    if (conversationSummary) {
      messages.push(new SystemMessage(`对话历史摘要: ${conversationSummary}`));
    }

    // 添加最近的对话历史
    for (const message of recentMessages) {
      if (message.role === 'user') {
        messages.push(new HumanMessage(message.content));
      } else if (message.role === 'assistant') {
        messages.push(new AIMessage(message.content));
      }
    }

    // 添加当前用户消息
    messages.push(new HumanMessage(currentMessage));

    return messages;
  }

  /**
   * 验证上下文长度
   */
  private async validateContextLength(messages: any[]): Promise<any[]> {
    const estimatedTokens = this.estimateTokenCount(messages);

    if (estimatedTokens <= this.maxContextLength) {
      return messages;
    }

    // 如果超出长度限制，逐步移除较早的消息
    const systemMessages = messages.filter(msg => msg instanceof SystemMessage);
    const otherMessages = messages.filter(
      msg => !(msg instanceof SystemMessage)
    );

    // 保留系统消息和最近的几条消息
    const recentCount = Math.min(6, otherMessages.length);
    const recentMessages = otherMessages.slice(-recentCount);

    return [...systemMessages, ...recentMessages];
  }

  /**
   * 估算token数量
   */
  private estimateTokenCount(messages: any[]): number {
    // 简单的token估算：中文字符 * 1.5 + 英文单词 * 1
    let totalChars = 0;

    for (const message of messages) {
      const content = message.content || '';
      totalChars += content.length;
    }

    // 粗略估算：平均每个字符约1.2个token
    return Math.ceil(totalChars * 1.2);
  }

  /**
   * 分析用户意图
   */
  async analyzeUserIntent(
    message: string,
    context: ChatMessage[]
  ): Promise<{
    intent: string;
    confidence: number;
    entities: string[];
    needsRAG: boolean;
  }> {
    // 简单的意图识别逻辑
    const intents = {
      question: /[？?]|什么|如何|怎么|为什么|哪里|谁|何时/,
      request: /请|帮我|能否|可以|希望/,
      greeting: /你好|hi|hello|早上好|下午好|晚上好/i,
      thanks: /谢谢|感谢|thank/i,
      document_query: /文档|资料|内容|查找|搜索/,
    };

    let detectedIntent = 'general';
    let confidence = 0.5;

    for (const [intent, pattern] of Object.entries(intents)) {
      if (pattern.test(message)) {
        detectedIntent = intent;
        confidence = 0.8;
        break;
      }
    }

    // 简单的实体提取
    const entities = this.extractEntities(message);

    // 判断是否需要RAG
    const needsRAG =
      detectedIntent === 'document_query' ||
      entities.length > 0 ||
      /文档|资料|内容|查找|搜索|具体|详细/.test(message);

    return {
      intent: detectedIntent,
      confidence,
      entities,
      needsRAG,
    };
  }

  /**
   * 简单的实体提取
   */
  private extractEntities(text: string): string[] {
    const entities: string[] = [];

    // 提取可能的关键词
    const keywords = text.match(/[\u4e00-\u9fa5a-zA-Z]{2,}/g) || [];

    // 过滤常见词汇
    const stopWords = [
      '什么',
      '如何',
      '怎么',
      '为什么',
      '哪里',
      '可以',
      '能否',
      '请问',
    ];

    for (const keyword of keywords) {
      if (!stopWords.includes(keyword) && keyword.length > 1) {
        entities.push(keyword);
      }
    }

    return entities.slice(0, 5); // 最多返回5个实体
  }

  /**
   * 构建用户画像
   */
  private buildUserProfile(messages: ChatMessage[], userId: string) {
    const userMessages = messages.filter(m => m.role === 'user');
    const recentTopics = userMessages
      .slice(-5)
      .map(m => m.content.substring(0, 50))
      .filter(content => content.length > 10);

    return {
      preferredTone: 'professional',
      complexityLevel: userMessages.length > 10 ? 'advanced' : 'beginner',
      interactionHistory: recentTopics,
    };
  }

  /**
   * 获取意图显示名称
   */
  private getIntentDisplayName(intent: UserIntent): string {
    const intentNames = {
      [UserIntent.QUESTION]: '询问问题',
      [UserIntent.INSTRUCTION]: '指令请求',
      [UserIntent.CONVERSATION]: '日常对话',
      [UserIntent.CLARIFICATION]: '澄清说明',
      [UserIntent.COMPLAINT]: '投诉抱怨',
      [UserIntent.PRAISE]: '表扬赞美',
      [UserIntent.HELP]: '寻求帮助',
      [UserIntent.INFORMATION]: '信息查询',
      [UserIntent.CREATIVE]: '创意创作',
      [UserIntent.ANALYSIS]: '分析评估',
      [UserIntent.UNKNOWN]: '未知意图',
    };
    return intentNames[intent] || '未知';
  }

  /**
   * 获取语调显示名称
   */
  private getToneDisplayName(tone: string): string {
    const toneNames = {
      formal: '正式',
      casual: '随意',
      empathetic: '同理心',
      professional: '专业',
      creative: '创意',
    };
    return toneNames[tone as keyof typeof toneNames] || tone;
  }

  /**
   * 获取长度显示名称
   */
  private getLengthDisplayName(length: string): string {
    const lengthNames = {
      brief: '简洁',
      moderate: '适中',
      detailed: '详细',
    };
    return lengthNames[length as keyof typeof lengthNames] || length;
  }

  /**
   * 获取结构显示名称
   */
  private getStructureDisplayName(structure: string): string {
    const structureNames = {
      direct: '直接回答',
      explanatory: '解释说明',
      step_by_step: '分步骤',
      conversational: '对话式',
    };
    return (
      structureNames[structure as keyof typeof structureNames] || structure
    );
  }

  /**
   * 获取个性化响应配置
   */
  getPersonalizedConfig(userHistory: ChatMessage[]): {
    temperature: number;
    maxTokens: number;
    style: string;
  } {
    // 基于用户历史调整响应风格
    const messageCount = userHistory.length;
    const avgMessageLength =
      userHistory.reduce((sum, msg) => sum + msg.content.length, 0) /
        messageCount || 0;

    let temperature = 0.7;
    let maxTokens = 2000;
    let style = 'balanced';

    // 根据用户习惯调整参数
    if (avgMessageLength > 100) {
      // 用户喜欢详细回答
      temperature = 0.6;
      maxTokens = 3000;
      style = 'detailed';
    } else if (avgMessageLength < 30) {
      // 用户喜欢简洁回答
      temperature = 0.8;
      maxTokens = 1000;
      style = 'concise';
    }

    return { temperature, maxTokens, style };
  }
}

// 导出单例实例
export const conversationContextManager = new ConversationContextManager();
